#! /bin/bash

agent_config=$1
space='/usr/local/apm'
apm_demo_url=''
javaagent_url='https://apm2-javaagent-cn-east-3.obs.cn-east-3.myhuaweicloud.com/apm2_javaagent/apm-javaagent-2.0.0.tar'


function installReidis {
  status=`sudo ps -ef | grep redis | grep -v "grep" | wc -l`
  if [ "${status}" -eq 0 ];then
    yum -y install redis*
    systemctl start redis
    systemctl status redis
  fi
}

function installMysql {
  mysql_status='sudo ps -ef | grep mysql | grep -v "grep" | wc -l'
   if [ "${mysql_status}" -eq 0 ];then
    yum install -y mariadb*
    systemctl start mariadb
    `ps -ef | grep mariadb`
    echo 'change password'
    mysqladmin -u root password "Huawei@2021"
  fi
}

function createDatabase {
    create database apm_demo;
    use database apm_demo;
    # shellcheck source=/dev/null
    source /usr/local/apm/package/BOOT-INF/classes/sql/merchandise.sql
    # shellcheck source=/dev/null
    source /usr/local/apm/package/BOOT-INF/classes/sql/merchandise_ref_detail.sql
    # shellcheck source=/dev/null
    source /usr/local/apm/package/BOOT-INF/classes/sql/merchandise_stock.sql
    # shellcheck source=/dev/null
    source /usr/local/apm/package/BOOT-INF/classes/sql/orders.sql
    # shellcheck source=/dev/null
    source /usr/local/apm/package/BOOT-INF/classes/sql/shopping_carts.sql
}

function installJDK {
    jdk_status='sudo ps -ef | grep java | grep -v "grep" | wc -l'
    if [ "${jdk_status}" -eq 0 ];then
      yum install java-1.8.0*
      java -version
    fi
}

function wgetApmDemo {
      wget -P ${space} ${apm_demo_url}
      jar -xvf apm2-demo-1.0.0.jar
}

function wgetAgent {
  if [ ! -d $space ]
  then
    mkdir /usr/local/apm
  fi
  cd $space || return
  if [ -d 'apm-javaagent' ];
    then echo "apm-javaagent exist"
    else
      echo "downlod java_agent"
      wget ${javaagent_url}
      tar -xvf apm-javaagent-2.0.0.tar
      cd apm-javaagent || return
      \cp $space/'package/BOOT-INF/classes/script/confg/apm_config/'"$agent_config"'.config' agent_config.confg
  fi
}

 echo "openjdk start install"
installJDK
 echo "mysql start install"
installMysql
  echo "redis start install"
installReidis
  echo "init demo"
wgetApmDemo
  echo "init agent"
wgetAgent